package org.lzy.shop.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.transition.Fade
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.kongzue.dialogx.dialogs.WaitDialog
import kotlinx.coroutines.launch
import org.lzy.shop.Constant
import org.lzy.shop.R
import org.lzy.shop.theme.ThemeManager
import org.lzy.shop.util.DataStoreUtils
import org.lzy.shop.util.LanguageUtil
import org.lzy.shop.util.ToastUtil


/**
 * 封装了通用的 init 方法，初始化布局，加载弹框等方法，提供了原始的添加布局的方式
 */
abstract class BaseActivity<VB: ViewBinding>(val block:(LayoutInflater) -> VB) : AppCompatActivity(){

    private var _binding: VB? = null

    val binding: VB
        get() = requireNotNull(_binding) { "biding 已被销毁" }


    override fun onCreate(savedInstanceState: Bundle?) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE)
        super.onCreate(savedInstanceState)
        _binding=block(layoutInflater)
        setContentView(binding.root)
        // 初始化主题管理器
        ThemeManager.init(this)
        initView()
        requestData()
        initData()
        allClick()
        // 启用窗口内容过渡
        window.enterTransition = Fade()
        window.exitTransition = Fade()
    }

    override fun onResume() {
        super.onResume()
        loadTheme()
    }

    fun loadTheme(){
        // 在Activity恢复时，应用保存的主题颜色
        if (ThemeManager.getCurrentThemeColor() != 0) {
            ThemeManager.applyThemeToActivity(this, ThemeManager.getCurrentThemeColor())
        }
        // 应用字体大小设置到整个Activity
        ThemeManager.applyFontSizeToActivity(this)
    }


    /**
     * 初始化布局
     *
     */
    abstract fun initView()

    /**
     * 初始化数据
     */
    abstract fun initData()

    /**
     * 请求后台返回数据统一在这个方法调用，该页面不需要请求则不用在该方法里写
     */
    protected abstract fun requestData()

    /**
     * 设置所有的点击事件回调监听
     * */
    abstract fun allClick()

    // LiveData扩展函数 - 自动适配不同场景
    //用lifecycleScope.launch + repeatOnLifecycle确保LiveData的观察与组件生命周期正确绑定 ，避免内存泄漏和不必要的资源消耗
    // 使用repeatOnLifecycle来观察LiveData，确保在Activity不在前台时停止观察

    fun <T> LiveData<T>.observeWithLifecycle(
        owner: LifecycleOwner,
        state: Lifecycle.State = Lifecycle.State.STARTED,
        observer: Observer<T>
    ) {
        owner.lifecycleScope.launch {
            repeatOnLifecycle(state) {
                observe(owner, observer)
            }
        }
    }

    // 简化版（默认STARTED状态）
    fun <T> LiveData<T>.observeSimplified(owner: LifecycleOwner, observer: Observer<T>) {
        observe(owner, observer)
    }

    override fun attachBaseContext(context: Context) {
        val language= DataStoreUtils.getConfig(Constant.SP_LANGUAGE,0)
        super.attachBaseContext(LanguageUtil.attachBaseContext(context, language.toString()))
    }

    //设置标题，就没必要每个界面找id在赋值
    fun setTitleText(title: String?) {
        val titileTv = findViewById<TextView>(R.id.title)
        titileTv.text = title
    }

    /**
     * 加载中……弹框
     */
    fun showLoading() {
        WaitDialog.show(this, "")
    }

    /**
     * 关闭提示框
     */
    fun dismissLoading() {
        WaitDialog.dismiss()
    }


    //跳转Activity
    fun startActivity(clazz: Class<*>?) {
        val intent = Intent(this, clazz)
        startActivity(intent)
    }

    //跳转Activity并finish
    fun startKillActivity(clazz: Class<*>?) {
        val intent = Intent(this, clazz)
        startActivity(intent)
        finish()
    }

    //带bundle的跳转界面
    fun startActivity(clazz: Class<*>, bundle: Bundle) {
        val intent = Intent()
        intent.setClass(this, clazz)
        intent.putExtras(bundle)
        startActivity(intent)
    }

    fun getResString(resid: Int): String {
        return  resources.getString(resid)
    }

    fun getResColor(resid: Int): Int {
        return ContextCompat.getColor(this, resid)
    }

    /**
     * 配置RecyclerView，支持更灵活的参数设置
     * @param recycleView RecyclerView控件
     * @param isLinear 是否为线性布局
     * @param spanCount 网格布局的列数
     * @param orientation 线性布局的方向
     */
    fun configureRecyclerView(
        recycleView: RecyclerView,
        isLinear: Boolean = true,
        spanCount: Int = 3,
        orientation: Int = RecyclerView.VERTICAL
    ) {
        try {
            recycleView.layoutManager = if (isLinear) {
                LinearLayoutManager(this, orientation, false)
            } else {
                GridLayoutManager(this, spanCount)
            }
            recycleView.itemAnimator = null
            recycleView.setHasFixedSize(true)
        } catch (e: Exception) {

        }
    }

    //标题左边按钮统一设点击事件
    fun back(view: View?) {
        finish()
    }

    fun showToast(msg: String) {
        ToastUtil.show(msg)
    }

    // 添加成功Toast方法
    fun showSuccessToast(msg: String?) {
        ToastUtil.showSuccess(msg)
    }

    // 添加错误Toast方法
    fun showErrorToast(msg: String) {
        ToastUtil.showError(msg)
    }

    fun showEmptyView(): View? {
        return LayoutInflater.from(this).inflate(R.layout.empty_view, null)
    }



    override fun onDestroy() {
        super.onDestroy()
        // 在 Activity 销毁时，清空 binding 引用，防止内存泄漏
        _binding = null
    }
}